'''
https://leetcode.cn/problems/minimum-absolute-difference-in-bst/?envType=study-plan-v2&envId=top-interview-150
'''

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def getMinimumDifference(self, root: TreeNode) -> int:
        pre = float('-inf')
        res = float('inf')
        def f(root):
            if not root: return
            nonlocal pre, res
            f(root.left)
            res = min(res, root.val - pre)
            pre = root.val
            f(root.right)
        f(root)
        return res
    def getMinimumDifference2(self, root: TreeNode) -> int:
        def f(root):
            if not root: return float('inf'), float('-inf'), float('inf')
            lmin, lmax, lmin_diff = f(root.left)
            rmin, rmax, rmin_diff = f(root.right)
            minv = min(lmin, rmin, root.val)
            maxv = max(lmax, rmax, root.val)
            min_diff = min(lmin_diff, rmin_diff, abs(root.val - lmax), abs(rmin -root.val) )
            return minv, maxv, min_diff
        return f(root)[2]

